package service

import (
	"context"
	"time"

	"github.com/example/video_backend/internal/model"
	"github.com/example/video_backend/internal/repository"
)

// PlayHistoryService 播放历史服务接口
type PlayHistoryService interface {
	AddOrUpdatePlayHistory(ctx context.Context, userID, videoID uint, progress float64) error
	DeletePlayHistory(ctx context.Context, historyID uint) error
	ClearUserPlayHistory(ctx context.Context, userID uint) error
	GetUserPlayHistory(ctx context.Context, userID uint, page, pageSize int) ([]*model.PlayHistory, int64, error)
}

// playHistoryService 实现PlayHistoryService接口
type playHistoryService struct {
	playHistoryRepo repository.PlayHistoryRepository
}

// NewPlayHistoryService 创建播放历史服务实例
func NewPlayHistoryService(playHistoryRepo repository.PlayHistoryRepository) PlayHistoryService {
	return &playHistoryService{playHistoryRepo: playHistoryRepo}
}

// AddOrUpdatePlayHistory 添加或更新播放历史
func (s *playHistoryService) AddOrUpdatePlayHistory(ctx context.Context, userID, videoID uint, progress float64) error {
	// 创建或更新播放历史
	history := &model.PlayHistory{
		UserID:       userID,
		VideoID:      videoID,
		Progress:     progress,
		LastPlayedAt: time.Now(),
	}

	return s.playHistoryRepo.CreateOrUpdate(ctx, history)
}

// DeletePlayHistory 删除播放历史记录
func (s *playHistoryService) DeletePlayHistory(ctx context.Context, historyID uint) error {
	return s.playHistoryRepo.Delete(ctx, historyID)
}

// ClearUserPlayHistory 清空用户的播放历史
func (s *playHistoryService) ClearUserPlayHistory(ctx context.Context, userID uint) error {
	return s.playHistoryRepo.ClearUserHistory(ctx, userID)
}

// GetUserPlayHistory 获取用户的播放历史列表
func (s *playHistoryService) GetUserPlayHistory(ctx context.Context, userID uint, page, pageSize int) ([]*model.PlayHistory, int64, error) {
	return s.playHistoryRepo.GetUserHistory(ctx, userID, page, pageSize)
}
